package com.mulanweb.handler.wechat;

import com.mulanweb.api.module.model.User;
import com.mulanweb.db.common.Constant;
import com.mulanweb.handler.PostHandler;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.mulanweb.utils.StringFormatterUtil.enCodeString;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class UserHandler {


    /**
     * 用户关注微信号公众号时调用此方法保存用户
     *
     * @param openid 微信生成的用户唯一id
     * @return
     */
    public static Boolean subscribe(String openid) throws IOException {
        //User user = User.dao.findByIdLoadColumns(openid,"open_id");
        User existUser = User.dao.findFirst("select * from user where open_id = ? ", openid);
        User user = getUserDetail(openid);
        if (existUser != null) {
            try {
                user.setId(existUser.getId());
                user.setWechatNickname(enCodeString(user.getWechatNickname()));
                return user.update();
            } catch (Exception e) {
                user.setWechatNickname("Constant.Mulan.DEFAULT_NAME");
                user.setCreateTime(new Date());
                user.update();
                e.printStackTrace();
                return false;
            }
        } else {
            try {
                user.setCreateTime(new Date());
                return user.save();
            } catch (Exception e) {
                user.setWechatNickname("新途用户");
                user.setCreateTime(new Date());
                user.save();
                e.printStackTrace();
                return false;
            }

        }
    }

    /**
     * 用户取消关注公众号时调用此方法逻辑删除用户
     *
     * @param openid 微信生成的用户唯一id
     * @return
     */
    public static Boolean unSubscribe(String openid) {
        User user = User.dao.findFirst("select * from user where open_id = ?", openid);
        if (user != null) {
            user.setStatusId(0);
            user.setSubscribeTime(new Date());
            return user.update();
        }
        return false;
    }


    /**
     * 设置用户地理位置
     *
     * @param openid    微信生成的用户唯一id
     * @param longitude 经度
     * @param latitude  维度
     * @param precision 精度
     * @return 操作成功或失败
     */
    public static Boolean setLocation(String openid, String longitude, String latitude, String precision) {
        User user = User.dao.findFirst("select * from user where open_id = ?", openid);
        if (null != user) {
            user.setLongitude(longitude);
            user.setLatitude(latitude);
            user.setPrecision(precision);
            return user.update();
        }
        return false;
    }


    /**
     * 根据openId 获取用户信息详情
     *
     * @param openId 微信对用户的编码
     * @return 一个无Id 的  Userd 对象
     */
    public static User getUserDetail(String openId) {
        return getUserDetail(openId, null);
    }

    /**
     * @param openId 根据openId 获取用户信息详情
     * @param lang   返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语 默认为中文简体
     * @return 一个无Id 的  Userd 对象
     */
    public static User getUserDetail(String openId, String lang) {
        lang = lang != null ? lang : "zh_CN";
        User user = new User();
        Map<String, String> para = null;
        if (openId != null) {
            para = PostHandler.post(Constant.WeChatFinalValue.getGetUserDetailUrl(TokenHandler.getAccessToken(), openId, lang));
            if (para != null && (!(para.containsKey("errcode")) && (!"0".equals(para.get("subscribe").toString())))) {
                user.setStatusId(Integer.parseInt(para.get("subscribe")));
                user.setOpenId(para.get("openid"));
                user.setWechatNickname(para.get("nickname"));
                user.setSex(Integer.parseInt(para.get("sex")));
                user.setCity(para.get("city"));
                user.setCountry(para.get("country"));
                user.setProvince(para.get("province"));
                user.setLogoPath(para.get("headimgurl").replace("\\", ""));
                user.setSubscribeTime(new Date(Long.parseLong(para.get("subscribe_time")) * 1000));
                user.setRemark(para.get("remark"));
                user.setGroupId(Long.parseLong(para.get("groupid")));
            } else {
                String errorCode = para.get("errcode");
                //todo 错误代码保存到错误日志中
                return null;
            }
            return user;
        }
        return null;
    }

    /**
     * 同步用户信息
     *
     * @param openId
     * @return
     */
    public static boolean synchronizationUserInfo(String openId) {
        User user = getUserDetail(openId);
        User user2 = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ?", openId);
        user.setId(user2.getId());
        user.setModifyTime(new Date());
        try {
            user.setWechatNickname(enCodeString(user.getWechatNickname()));
            return user.update();
        } catch (Exception e) {
            user.setWechatNickname("新途用户");
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 检查用户是否存在或关注
     *
     * @param openId 微信用户主键
     * @return 存在或不存在
     */
    public static boolean userNotNull(String openId) {
        User user2 = getUserDetail(openId);
        if (user2 != null) {
            User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ?", openId);
            if (user == null) {
                user2.setModifyTime(new Date());
                user2.setCreateTime(new Date());
                try {
                    user2.setWechatNickname(enCodeString(user2.getWechatNickname()));
                    return user2.save();
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
            user2.setId(user.getId());
            user2.setModifyTime(new Date());
            try {
                user2.setWechatNickname(enCodeString(user2.getWechatNickname()));
                user2.update();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } else {
            return false;
        }
    }
}
